#!/usr/bin/env python
# -*- coding: utf-8 -*-

import debug
import sys
import os
import ConfigParser
import imp
import inspect
import logging

class Controller(object):
    QUERY_FRAME_ALL   = 0x00    # 全件取得
    QUERY_FRAME_FIRST = 0x10    # 一番古いものを取得
    QUERY_FRAME_LAST  = 0x20    # 一番新しいものを取得

    @debug.entry
    def __init__(self, config_path='../camfw.conf'):
        '''
            コンストラクタ
            コントローラがプラグインを探す
        '''
        if config_path is None:
            return
        self.__config = {}
        self.__config['path']   = config_path
        self.__config['object'] = ConfigParser.SafeConfigParser()
        self.__config['object'].read( config_path )

        self.__engine = {}
        self.__engine['name']   = self.__config['object'].get( 'global', 'storage.engine' )
        self.__engine['object'] = self.__get_plugin_object( self.__engine['name'] )

        self.engine = self.__engine['object'](self.__config)

    @debug.entry
    def __get_plugin_object(self, engine):
        '''
            コンフィグで指定されたプラグインオブジェクトをインスタンス化する
        '''
        if engine is None:
            return None
        mydir = os.path.dirname( os.path.abspath(__file__) )
        sys.path.append( mydir + '/plugins' )
        mfile, mpathname, mdescription = imp.find_module( engine )
        module  = imp.load_module( engine, mfile, mpathname, mdescription )
        classdicts = inspect.getmembers( module, inspect.isclass )
        for classdict in classdicts:
            if classdict[0] == engine:
                return classdict[1]
        return None

    @debug.entry
    def get_frame_list(self, target, query=None, fext='.jpg'):
        '''
            保存されたフレーム列挙メソッドの呼び出し
        '''
        if query is None:
            return self.engine.get_frame_list_all(target, fext)
        elif isinstance(query, int):
            if query == Controller.QUERY_FRAME_ALL:
                return self.engine.get_frame_list_all(target, fext)
            elif query == Controller.QUERY_FRAME_FIRST:
                return self.engine.get_frame_list_first(target, fext)
            elif query == Controller.QUERY_FRAME_LAST:
                return self.engine.get_frame_list_last(target, fext)
        elif isinstance(query, list):
            return self.engine.get_frame_list_range(target, query, fext)

    @debug.entry
    def save_frame(self, target, fileobj, fext='.jpg', uniqname=None, options={'async':False} ):
        '''
            フレームを保存する
        '''
        self.engine.save_frame(target, fileobj, fext, uniqname, options)

    @debug.entry
    def get_frame(self, framestring, fext='.jpg'):
        '''
            フレームの実体を返す
        '''
        return self.engine.get_frame(framestring, fext)


if __name__ == '__main__':
    '''
        静的解析用コード
        camfwd.pyからは実行されません
    '''
    c = Controller('../../camfw.conf')

    target = 'cam1'

    print c.get_frame_list(target)
    print c.get_frame_list(target, Controller.QUERY_FRAME_ALL)
    print c.get_frame_list(target, Controller.QUERY_FRAME_FIRST)
    print c.get_frame_list(target, Controller.QUERY_FRAME_LAST)
    frames = c.get_frame_list(target,
            ['2013-07-18T11:26:28.258138Z', '2013-07-18T11:26:28.558070Z'])    #RANGE
    for frame in frames:
        obj = c.get_frame(frame)
        print len(obj)


